'use strict';

const path = require('path')
const Package = require('@lio-imooc-cli-dev/package')
const log = require('@lio-imooc-cli-dev/log')

const SETTINGS = {
    // init: '@lio-imooc-cli-dev/init'
    // init: '@imooc-cli/init'
    init: '@lio-cli/init'
}

const CACHE_DIR = 'dependencies'

// lio-imooc-cli-dev init --targetPath D:\software\java\workspace\lio-imooc-cli-dev --debug test-project --force
// lio-imooc-cli-dev init test-project --force --debug
async function exec() {
    let targetPath = process.env.CLI_TARGET_PATH
    const homePath = process.env.CLI_HOME_PATH
    let storeDir = ''
    let pkg
    log.verbose('targetPath', targetPath)
    log.verbose('homePath', homePath)

    const cmdObj = arguments[arguments.length - 1]
    // console.log(cmdObj.force) 如果命令有--force，输出true
    const cmdName = cmdObj.name()
    const packageName = SETTINGS[cmdName]
    const packageVersion = 'latest'

    if (!targetPath) {
        // 生成缓存路径
        targetPath = path.resolve(homePath, CACHE_DIR)
        storeDir = path.resolve(targetPath, 'node_modules')
        log.verbose('targetPath', targetPath);
        log.verbose('storeDir', storeDir);

        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion
        })
        if (await pkg.exists()) {
            // 更新package
            console.log('更新package')
            // pkg.update()
        } else {
            // 安装package
            await pkg.install()
        }
    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        })
    }
    const rootFile = pkg.getRootFilePath()
    // lio-imooc-cli-dev init test-project --force --debug
    if (rootFile) {
        require(rootFile).apply(null, arguments)
    }
}

module.exports = exec;
